﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Security;

using CMS.BL;
using CMS.BL.Entity;
using CMS.Services;
using CMS.UI.Common;
using CMS.UI.Models;
using CMS.UI.Security;
using CMS.Utils;
using CMS.Utils.Cryptography;
using Recaptcha.Web;
using Recaptcha.Web.Mvc;
using System.Data.Entity.Validation;
using CMS.Utils.Diagnostics;

namespace CMS.UI.Controllers
{
    [Authentication]
    public class WebsiteController : BaseController
    {
        private readonly IDomain DomainService;
        private readonly IWebContent WebContentService;
        private readonly IWebPages WebPagesService;
        private readonly IUser UserService;

        public WebsiteController(IDomain domainService,
            IWebContent webContentService,
            IWebPages webPagesService,
            IUser userService)
            : base(domainService)
        {
            this.DomainService = domainService;
            this.WebContentService = webContentService;
            this.WebPagesService = webPagesService;
            this.UserService = userService;
        }

        [AllowAnonymous]
        public ActionResult Index()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult Content(int sectionID = 0, int contentID = 0)
        {
            sectionID = Request.Url.LocalPath == "/" && this.Domain != null ? this.Domain.DO_HomePageID : sectionID;
            var user = this.AdminUser != null ? this.AdminUser.IsAdmn : false;
            tbl_Content content = WebContentService.GetContentBySitemapUrl(Request.Url.LocalPath, this.DomainID, sectionID, contentID, user);
            if (content == null)
                throw new HttpException(404, "Page Not Found");

            tbl_Settings settings = DomainService.GetSettingsByValue(content.tbl_SiteMap.SM_URL, this.DomainID);
            if (Request.Url.LocalPath == "/" && settings != null)
            {
                SettingsKey key = (SettingsKey)Enum.Parse(typeof(SettingsKey), settings.SE_Variable);
                switch (key)
                {
                    case SettingsKey.adNewsPath:
                        return Blog(String.Empty, String.Empty, String.Empty);
                    case SettingsKey.adSitemapPath:
                        return Sitemap();
                    case SettingsKey.adTestimonialsPath:
                        return Testimonials();
                }
            }

            ContentModel contentModel = ContentModelFactory(content);
            this.ViewBag.Title = content.C_Title;

            return View(contentModel);
        }

        [AllowAnonymous]
        public ActionResult Breadcrumbs(string url = "")
        {
            url = String.IsNullOrEmpty(url) ? this.Request.Url.AbsolutePath : url;
            ViewBag.CompanyName = this.Domain != null ? this.Domain.DO_CompanyName : string.Empty;
            return PartialView("/Views/Partials/Breadcrumbs.cshtml", FindBreadcrumbByUrl(url, GetMenuOrdered(true, true, false, false, true, true)));
        }

        [AllowAnonymous]
        public ActionResult Menu()
        {
            return PartialView("/Views/Partials/Menu.cshtml", GetMenuOrdered(true, false, false));
        }

        [AllowAnonymous]
        public ActionResult Footer()
        {
            return PartialView("/Views/Partials/Footer.cshtml",
                new FooterModel()
                {
                    WebsiteMenu = GetMenuOrdered(false, true, false)
                });
        }

        [AllowAnonymous]
        public ActionResult Sitemap()
        {
            this.ViewBag.SitemapPage = WebContentService.GetContentBySitemapUrl(DomainService.GetSettingsValue(SettingsKey.adSitemapPath).TrimEnd('/'), this.DomainID);
            return View("Sitemap", GetMenuOrdered(false, false, true, true, true, true));
        }

        [AllowAnonymous]
        public ActionResult WebsiteUrls(string time)
        {
            var list = CreateElements(GetMenuAllOrdered()).OrderBy<LinkListItem, string>(x => x.title).ToList();
            return PartialView("/Views/Partials/UrlsList.cshtml", list);
        }

        [AllowAnonymous]
        public ActionResult CustomEditorObjects(int currentDomainID)
        {
            if (currentDomainID == 0)
            {
                currentDomainID = DomainID;
            }
            List<Array> customObjects = new List<Array>();
            // tinyMCE: link_list
            customObjects.Add(CreateElements(GetMenuOrdered(false, false, true)).OrderBy<LinkListItem, string>(x => x.title).ToArray());
            // tinyMCE: customform_list
            Array customForms = WebPagesService.GetAllFormsByDomainID(currentDomainID).OrderBy(f => f.F_Name).Select(f => new LinkListItem()
            {
                title = f.F_Name,
                value = f.FormID.ToString()
            }).ToArray();
            customObjects.Add(customForms);

            Array customObjectsArray = customObjects.ToArray<Array>();
            return Json(new
            {
                customObjectsArray
            }, JsonRequestBehavior.AllowGet);
        }

        [AllowAnonymous]
        public ActionResult XMLSitemap()
        {
            if (!Directory.Exists(Server.MapPath(SettingsManager.Sitemap.Folder)))
                Directory.CreateDirectory(Server.MapPath(SettingsManager.Sitemap.Folder));

            string domain = this.Domain != null ? "http://" + this.Domain.DO_Domain : string.Empty;
            string path = Server.MapPath(SettingsManager.Sitemap.Folder) + SettingsManager.Sitemap.File;
            SitemapXML.Create(GetMenuOrdered(false, false, true, true, true, true), path, domain);
            return File(path, "text/xml");
        }

        [AllowAnonymous]
        public ActionResult Search(string keyword)
        {
            List<tbl_Content> textsContents = WebContentService.SearchContent(keyword, this.DomainID);
            this.ViewBag.Header = String.Format("Search Results for '{0}'", keyword);
            this.ViewBag.BlogUrl = "/" + DomainService.GetSettingsValue(SettingsKey.adNewsPath).Trim('/');
            this.ViewBag.NoNewsFound = (textsContents.Count() == 0) ? String.Format("No Search Results for '{0}'", keyword) : string.Empty;
            return View("SearchResults", textsContents);
        }

        [AllowAnonymous]
        public ActionResult NotFound404()
        {
            return View(GetMenuOrdered(false, false, true, true, true, true));
        }

        #region Blog

        [AllowAnonymous]
        public ActionResult Blog(string year, string month, string title)
        {
            var blogUrl = DomainService.GetSettingsValue(SettingsKey.adNewsPath).Trim('/');
            this.ViewBag.BlogUrl = blogUrl;
            if (!String.IsNullOrEmpty(year) && !String.IsNullOrEmpty(month) && !String.IsNullOrEmpty(title))
            {
                tbl_Content blog = WebContentService.GetContentBySitemapUrl(String.Format("/{0}/{1}/{2}", year, month, title), this.DomainID);
                if (blog == null)
                    throw new HttpException(404, "Page Not Found");

                this.ViewBag.Title = blog.C_Title;
                this.ViewBag.ShareThisID = this.Domain != null ? this.Domain.DO_ShareThis : String.Empty;
                this.ViewBag.Content = ContentModelFactory(blog);
                return View("BlogItem", blog);
            }
            else
            {
                this.ViewBag.BlogPage = WebContentService.GetContentBySitemapUrl("/" + blogUrl, this.DomainID);
                if (!String.IsNullOrEmpty(year) && !String.IsNullOrEmpty(month) && String.IsNullOrEmpty(title))
                {
                    List<tbl_Content> blogs = WebContentService.GetContentBySitemapDate(year, month, this.DomainID);
                    this.ViewBag.Title = ParseDate(year, month).ToString("yyyy MMMM");
                    this.ViewBag.Header = String.Format("Archive For '{0}'", ParseDate(year, month).ToString("MMMM, yyyy"));
                    this.ViewBag.NoNewsFound = (blogs == null || blogs.Count == 0) ? String.Format("No news for '{0}'", this.ViewBag.Title) : string.Empty;
                    return View("Blog", blogs);
                }
                else
                {
                    List<tbl_Content> blogs = WebContentService.GetContentByContentType(ContentType.Blog, this.DomainID);
                    this.ViewBag.Title = String.Format("{0}'s Latest News", this.Domain != null ? this.Domain.DO_Domain : String.Empty);
                    this.ViewBag.Header = "Latest News";
                    this.ViewBag.NoNewsFound = (blogs == null || blogs.Count == 0) ? "No latest news" : string.Empty;
                    return View("Blog", blogs);
                }
            }
        }

        [AllowAnonymous]
        public ActionResult BlogCategory(string name)
        {
            List<tbl_Content> blogs = WebContentService.GetContentByCategoryUrl(name, this.DomainID);
            tbl_Categories category = WebContentService.GetCategoryByURL(name);
            this.ViewBag.Header = String.Format("Archive for the '{0}' Category", category != null ? category.CA_Title : name);
            this.ViewBag.Title = category != null ? category.CA_Title : name;
            this.ViewBag.NoNewsFound = (blogs == null || blogs.Count == 0) ? String.Format("No news for '{0}' category", name) : string.Empty;
            this.ViewBag.BlogUrl = DomainService.GetSettingsValue(SettingsKey.adNewsPath).Trim('/');
            this.ViewBag.BlogPage = WebContentService.GetContentBySitemapUrl(DomainService.GetSettingsValue(SettingsKey.adNewsPath).TrimEnd('/'), this.DomainID);
            return View("Blog", blogs);
        }

        [AllowAnonymous]
        public ActionResult BlogSearch(string keyword)
        {
            List<tbl_Content> blogs = WebContentService.GetContentByContentType(ContentType.Blog, this.DomainID).Where(c => (c.C_Content.Contains(keyword) || c.C_Title.Contains(keyword))).ToList();
            this.ViewBag.Header = String.Format("Search Results for '{0}'", keyword);
            this.ViewBag.NoNewsFound = blogs == null || blogs.Count() == 0 ? String.Format("No Search Results for '{0}'", keyword) : string.Empty;
            this.ViewBag.BlogPage = WebContentService.GetContentBySitemapUrl(DomainService.GetSettingsValue(SettingsKey.adNewsPath).TrimEnd('/'), this.DomainID);
            this.ViewBag.BlogUrl = DomainService.GetSettingsValue(SettingsKey.adNewsPath).Trim('/');
            return View("Blog", blogs);
        }

        [AllowAnonymous]
        public ActionResult BlogTag(string name)
        {
            List<tbl_Content> blogs = WebContentService.GetContentByTagUrl(name, this.DomainID);
            tbl_Tags tag = WebContentService.GetTagByURL(name);
            this.ViewBag.Header = String.Format("Posts Tagged '{0}'", tag != null ? tag.TA_Title : name);
            this.ViewBag.Title = name;
            this.ViewBag.BlogPage = WebContentService.GetContentBySitemapUrl(DomainService.GetSettingsValue(SettingsKey.adNewsPath).TrimEnd('/'), this.DomainID);
            this.ViewBag.BlogUrl = DomainService.GetSettingsValue(SettingsKey.adNewsPath).Trim('/');
            return View("Blog", blogs);
        }

        [AllowAnonymous]
        public ActionResult BlogSideBar()
        {
            this.ViewBag.Categories = WebContentService.GetAllCategoriesLive(this.DomainID);
            List<tbl_Content> blogs = WebContentService.GetContentByContentType(ContentType.Blog, this.DomainID);
            this.ViewBag.RecentPosts = (blogs != null) ?
                blogs.Take(SettingsManager.Blog.RecentItemsAmount).ToList() :
                new List<tbl_Content>();
            this.ViewBag.Archive = (blogs != null) ?
                blogs.Where(b => b.tbl_SiteMap.SM_Date.HasValue)
                    .Select(b => new DateTime(b.tbl_SiteMap.SM_Date.Value.Year, b.tbl_SiteMap.SM_Date.Value.Month, 1))
                    .Distinct().ToList() :
                new List<DateTime>();
            this.ViewBag.BlogUrl = DomainService.GetSettingsValue(SettingsKey.adNewsPath).Trim('/');
            return PartialView("/Views/Partials/BlogSideBar.cshtml");
        }

        [AllowAnonymous]
        public ActionResult CommentForm(int sitemapID)
        {
            this.ViewBag.SitemapID = sitemapID;
            this.ViewBag.PublicKey = DomainService.GetSettingsValue(SettingsKey.recaptcha_public_key);
            return PartialView("/Views/Partials/CommentForm.cshtml");
        }

        [AllowAnonymous]
        public ActionResult SaveComment(CommentModel comment)
        {
            RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper(DomainService.GetSettingsValue(SettingsKey.recaptcha_private_key, this.DomainID));
            if (String.IsNullOrEmpty(recaptchaHelper.Response))
            {
                return Json(new { error = "Captcha answer cannot be empty." }, "text/html");
            }

            RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
            if (recaptchaResult != RecaptchaVerificationResult.Success)
            {
                return Json(new { error = "Incorrect captcha answer." }, "text/html");
            }

            if (ModelState.IsValid)
            {
                tbl_Comments dbComment = WebContentService.SaveComment(comment.Name, comment.Email, comment.Website, comment.Message, comment.SitemapID, 0);
                if (dbComment == null)
                    return Json(new { success = false });

                string companyName = this.Domain != null ? this.Domain.DO_CompanyName : string.Empty;
                string domain = this.Domain != null ? this.Domain.DO_Domain : string.Empty;
                var postUrl = String.Format("http://{0}{1}", domain, dbComment.tbl_SiteMap.SM_URL);
                var adminUrl = String.Format("http://{0}{1}", domain, "/Admn/News");
                MailingService.SendNewComment(postUrl, adminUrl, companyName, domain, dbComment.tbl_SiteMap.tbl_Domains.DO_Email);
                return Json(new { success = comment != null }, "text/html");
            }
            return Json(new { success = false }, "text/html");
        }

        [AllowAnonymous]
        public ActionResult GetBlogRss()
        {
            List<tbl_Content> blogs = WebContentService.GetContentByContentType(ContentType.Blog, this.DomainID).Take(SettingsManager.Blog.RssItemsAmount).ToList();
            List<SyndicationItem> rssItems = new List<SyndicationItem>();
            foreach (var blogItem in blogs)
            {
                Uri url = new Uri("http://" + (this.Domain != null ? this.Domain.DO_Domain : String.Empty) + blogItem.tbl_SiteMap.SM_URL);
                var rssItem = new SyndicationItem(blogItem.C_Title, blogItem.C_Description, url, blogItem.ContentID.ToString(), DateTime.Now);
                rssItem.Authors.Add(new SyndicationPerson(blogItem.tbl_SiteMap.SM_NotifyEmail));
                rssItem.PublishDate = new DateTimeOffset(blogItem.tbl_SiteMap.SM_Date.GetValueOrDefault(DateTime.Now));
                rssItems.Add(rssItem);
            }

            SyndicationFeed feed = new SyndicationFeed(rssItems);
            if (this.Domain != null)
            {
                feed.Copyright = new TextSyndicationContent("Copyright 2009");
                feed.Description = new TextSyndicationContent("All the latest news from " + this.Domain.DO_CompanyName);
                feed.ImageUrl = null;
                feed.Language = "en-gb";
                feed.Links.Add(new SyndicationLink(new Uri("http://" + this.Domain.DO_Domain)));
                feed.Title = new TextSyndicationContent(this.Domain.DO_CompanyName);
            }

            return new RssResult(feed);
        }

        #endregion Blog


        #region Testimonials

        [AllowAnonymous]
        public ActionResult Testimonials()
        {
            List<tbl_Testimonials> testimonials = WebPagesService.GetAllTestimonialsLive();
            this.ViewBag.TestimonialsPage = WebContentService.GetContentBySitemapUrl(DomainService.GetSettingsValue(SettingsKey.adTestimonialsPath).TrimEnd('/'), this.DomainID);
            return View("Testimonials", testimonials);
        }

        [AllowAnonymous]
        public ActionResult TestimonialsPartial()
        {
            return PartialView("/Views/Partials/Testimonials.cshtml", WebPagesService.GetAllTestimonialsLive());
        }

        #endregion


        #region Custom / Contact Form

        [AllowAnonymous]
        public ActionResult ContactUsPartial()
        {
            this.ViewBag.ContactUsUrl = "/" + DomainService.GetSettingsValue(SettingsKey.adContactUsPath).Trim('/');
            return PartialView("/Views/Partials/ContactUs.cshtml");
        }

        [AllowAnonymous]
        public ActionResult SaveFormSubmission(FormCollection values)
        {
            string submittedFormID = values["FormID"];
            RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper(DomainService.GetSettingsValue(SettingsKey.recaptcha_private_key));
            if (String.IsNullOrEmpty(recaptchaHelper.Response))
            {
                return Json(new { error = "Captcha answer cannot be empty.", formID = submittedFormID }, "text/html");
            }

            RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
            if (recaptchaResult != RecaptchaVerificationResult.Success)
            {
                return Json(new { error = "Incorrect captcha answer.", formID = submittedFormID }, "text/html");
            }

            if (ModelState.IsValid)
            {
                string recipients = this.Domain != null ? this.Domain.DO_Email : String.Empty;
                if (!string.IsNullOrEmpty(values["RecipientEmail"]) && values["RecipientEmail"].Contains("@"))
                {
                    recipients = values["RecipientEmail"];
                }
                MailingService.SendCustomForm(WebPagesService.SaveFormSubmission(values, recipients, DateTime.UtcNow,
                    Convert.ToInt32(submittedFormID)), recipients);
                return Json(new { success = true, formID = submittedFormID }, "text/html");
            }
            return Json(new { success = false, formID = submittedFormID }, "text/html");
        }

        #endregion


        #region Private Methodes

        private bool IsActual(tbl_ProductPrice pp)
        {
            return pp.PR_EventEndDate.HasValue ? pp.PR_EventEndDate.Value > DateTime.Now : pp.PR_EventStartDate.GetValueOrDefault() > DateTime.Now;
        }

        private ContentModel ContentModelFactory(tbl_Content content)
        {
            return new ContentModel()
            {
                Content = content,
                CSS = content.tbl_SiteMap.SM_CSS,
                Html = content.C_Content,
                HtmlElements = String.IsNullOrEmpty(content.C_Content) ? new List<object>() :
                    ProcessHtmlContent(content.C_Content,
                        this.Domain != null ? this.Domain.DO_CompanyName : string.Empty,
                        DomainService.GetSettingsValue(SettingsKey.recaptcha_public_key))
            };
        }

        private List<WebsiteMenuModel> GetMenuOrdered(bool isMenu, bool isFooter, bool isSitemap, bool includeArticles = false, bool includeCategory = false, bool includeProducts = false)
        {
            List<tbl_SiteMap> sitemaps = WebContentService.GetSitemapByContentType(ContentType.Content, this.DomainID)
                .Where(sm => (isMenu && sm.SM_Menu) || (isFooter && sm.SM_Footer) || (isSitemap && sm.SM_Sitemap)).ToList();

            if (includeArticles)
                sitemaps.AddRange(WebContentService.GetSitemapByContentType(ContentType.Blog, this.DomainID).Where(b => b.SM_Live).OrderByDescending(b => b.SM_Date));
            return CreateChildMenuOrdered(sitemaps, 0);
        }

        private List<WebsiteMenuModel> GetMenuAllOrdered()
        {
            List<tbl_SiteMap> sitemaps = WebContentService.GetSitemapByContentType(ContentType.Content, this.DomainID).ToList();
            sitemaps.AddRange(WebContentService.GetSitemapByContentType(ContentType.Blog, this.DomainID).Where(b => b.SM_Live).OrderByDescending(b => b.SM_Date));

            return CreateChildMenuOrdered(sitemaps, 0);
        }

        private List<WebsiteMenuModel> CreateChildMenuOrdered(List<tbl_SiteMap> items, int parentID)
        {
            var menu = new List<WebsiteMenuModel>();
            var itemsFiltered = items.Where(sm => sm.SM_ParentID == parentID).OrderBy(sm => sm.SM_OrderBy).ToList();
            foreach (var item in itemsFiltered)
            {
                var content = item.tbl_Content.Where(c => c.C_Approved && !c.C_Deleted).OrderByDescending(c => c.C_ModificationDate).FirstOrDefault();
                string url = "";// item.tbl_ContentType.CTP_Value == ContentType.Blog.ToString() ? String.Format("/{0}{1}", DomainService.GetSettingsValue(SettingsKey.adNewsPath).Trim('/'), item.SM_URL) : item.SM_URL;
                if (item.tbl_ContentType.CTP_Value == ContentType.Blog.ToString())
                {
                    url = String.Format("/{0}{1}", DomainService.GetSettingsValue(SettingsKey.adNewsPath).Trim('/'), item.SM_URL);
                }
                else
                {
                    url = item.SM_URL;
                }
                if (content != null)
                {
                    menu.Add(new WebsiteMenuModel
                    {
                        Name = content.C_MenuText,
                        Url = url,
                        Title = content.C_Title,
                        ModificationDate = content.C_ModificationDate,
                        Priority = item.SM_Priority.GetValueOrDefault((decimal)0.5),
                        SubMenuItems = CreateChildMenuOrdered(items, item.SiteMapID)
                    });
                }
            }
            return menu;
        }

        private static List<LinkListItem> CreateElements(List<WebsiteMenuModel> pages)
        {
            List<LinkListItem> list = new List<LinkListItem>();
            foreach (var page in pages)
            {
                list.Add(new LinkListItem { title = page.Title, value = page.Url });

                if (page.SubMenuItems.Count > 0)
                    list.AddRange(CreateElements(page.SubMenuItems));
            }

            return list;
        }

        private List<WebsiteMenuModel> FindBreadcrumbByUrl(string url, List<WebsiteMenuModel> list)
        {
            List<WebsiteMenuModel> breadcrumbs = new List<WebsiteMenuModel>();
            foreach (WebsiteMenuModel m in list)
            {
                if (m.Url == url)
                {
                    breadcrumbs.Add(m);
                    return breadcrumbs;
                }
                else if (m.SubMenuItems != null && m.SubMenuItems.Count > 0)
                {
                    List<WebsiteMenuModel> sublist = FindBreadcrumbByUrl(url, m.SubMenuItems);
                    if (sublist.Count > 0)
                    {
                        breadcrumbs.Add(m);
                        breadcrumbs.AddRange(sublist);
                    }
                }
            }

            return breadcrumbs;
        }

        private DateTime ParseDate(string year, string month)
        {
            int y = 0, m = 0;
            int.TryParse(year, out y);
            int.TryParse(month, out m);
            return new DateTime(y, m, 1);
        }

        public List<object> ProcessHtmlContent(string content, string companyName, string publicKey)
        {
            List<object> htmlElems = new List<object>();
            string html = string.Empty;
            string tagCustomForm = string.Empty;
            string tagBeginCustomForm = "[%customform";
            string tagEndCustomForm = "/%]";
            int beginIdx = -1;
            int endIdx = -1;
            int cursor = 0;
            if (content == null)
                return null;
            do
            {
                if (content.Length >= beginIdx + tagBeginCustomForm.Length)
                {
                    beginIdx = content.IndexOf(tagBeginCustomForm, cursor);
                    endIdx = content.IndexOf(tagEndCustomForm, beginIdx + tagBeginCustomForm.Length);
                }

                if (beginIdx > -1 && endIdx > -1 && endIdx > beginIdx)
                {
                    if (cursor < beginIdx)
                    {
                        htmlElems.Add(content.Substring(cursor, beginIdx - cursor));
                    }

                    tagCustomForm = content.Substring(beginIdx, endIdx - beginIdx + tagEndCustomForm.Length);
                    FormModel formModel = GetFormModel(tagCustomForm, companyName, publicKey);
                    if (formModel != null)
                    {
                        htmlElems.Add(formModel);
                    }
                    beginIdx = endIdx + tagEndCustomForm.Length;
                    cursor = endIdx + tagEndCustomForm.Length;
                }
                else
                {
                    htmlElems.Add(content.Substring(cursor, content.Length - cursor));
                    beginIdx = endIdx = -1;
                }
            }
            while (beginIdx > -1 && endIdx > -1);

            return htmlElems;
        }

        private FormModel GetFormModel(string form, string companyName, string publicKey)
        {
            string formIDValue = GetAttributeValue(form, "data-formID");
            string formRecipientValue = GetAttributeValue(form, "data-recipient");

            int customFormID = 0;
            if (Int32.TryParse(formIDValue, out customFormID))
            {
                tbl_Form customform = WebPagesService.GetFormByID(customFormID);
                List<tbl_FormItem> customformitems = WebPagesService.GetAllFormItemsLiveByFormID(customFormID);
                if (customform != null && customformitems != null)
                {
                    return new FormModel()
                    {
                        FormID = customFormID,
                        DomainID = customform.F_DomainID,
                        Name = customform.F_Name,
                        Description = customform.F_Description,
                        FormItems = customformitems,
                        RecipientEmail = formRecipientValue,
                        CompanyName = companyName,
                        PublicKey = publicKey
                    };
                }
            }

            return null;
        }

        private string GetAttributeValue(string tag, string attributeName)
        {
            int beginIdx = tag.IndexOf(attributeName, 0);
            beginIdx = tag.IndexOf("\"", beginIdx);
            int endIdx = tag.IndexOf("\"", beginIdx + 1);

            return tag.Substring(beginIdx + 1, endIdx - beginIdx - 1).Trim();
        }

        #endregion
    }
}